{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a8a78494",
   "metadata": {},
   "outputs": [],
   "source": [
    "import tushare as ts\n",
    "import pandas as pd\n",
    "from datetime import datetime, timedelta\n",
    "\n",
    "ts_token = \"fb8c70426f1d5aea174eefd32219ab3b752bf5e8a89481a79450153b\"\n",
    "ts.set_token(ts_token)\n",
    "pro = ts.pro_api()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "213d4893",
   "metadata": {},
   "outputs": [],
   "source": [
    "ts_code = \"399005\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "5991677b",
   "metadata": {},
   "outputs": [],
   "source": [
    "ends = [\".SH\",\".SZ\",\".BJ\",\".HK\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "a0da7301",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_code_name(ts_code):\n",
    "    for e in ends:\n",
    "        code_name_df = pro.namechange(ts_code=ts_code+e, fields='ts_code,name,start_date,end_date,change_reason')\n",
    "        if not code_name_df.empty:\n",
    "            return df.head(1).to_dict(orient=\"records\")\n",
    "    return {\"status\":200,\"msg\":f\"获取【{ts_code}】股票代码后缀失败！\"}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "6660b9ee",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'status': 200, 'msg': '获取【399005】股票代码后缀失败！'}"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "get_code_name(ts_code)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "1516a26f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# df = pro.namechange(ts_code='600000.SH', fields='ts_code,name,start_date,end_date,change_reason')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "0bc8067c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'ts_code': '000001.SZ',\n",
       "  'name': '平安银行',\n",
       "  'start_date': '20120802',\n",
       "  'end_date': None,\n",
       "  'change_reason': '改名'}]"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.head(1).to_dict(orient=\"records\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91a0d157",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c75c2007",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_stock(start_date, end_date, code):\n",
    "    # 获取股票数据\n",
    "    df = pro.daily(ts_code=code, start_date=start_date, end_date=end_date).sort_values(by=\"trade_date\")\n",
    "    if df.empty:\n",
    "        return None\n",
    "    # 预测信息\n",
    "    forecast_msg = '暂无预测模型！'\n",
    "    result = {\n",
    "        \"stock_trade_days\": df[\"trade_date\"].values.tolist(),\n",
    "        \"stock_trade_data\": df[[\"open\", \"close\", \"low\", \"high\"]].values.tolist(),\n",
    "        \"MA5\": df[\"close\"].rolling(4).mean().map(lambda x: round(x, 3)).fillna(\"-\").tolist(),\n",
    "        \"MA10\": df[\"close\"].rolling(9).mean().map(lambda x: round(x, 3)).fillna(\"-\").tolist(),\n",
    "        \"MA20\": df[\"close\"].rolling(19).mean().map(lambda x: round(x, 3)).fillna(\"-\").tolist(),\n",
    "        \"MA30\": df[\"close\"].rolling(29).mean().map(lambda x: round(x, 3)).fillna(\"-\").tolist(),\n",
    "        \"forecast\": forecast_msg,\n",
    "        \"name\": code\n",
    "    }\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "43c41486",
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pro.daily(ts_code=\"000001.SZ\", start_date=\"20231101\", end_date=\"20231123\").sort_values(by=\"trade_date\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aeca98b7",
   "metadata": {},
   "outputs": [],
   "source": [
    "df.columns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d97f8691",
   "metadata": {},
   "outputs": [],
   "source": [
    "df2 = df.rename(columns={'ts_code':\"股票代码\", 'trade_date':\"交易日期\", 'open':\"开盘价\", 'high':\"最高价\", 'low':\"最低价\", 'close':\"收盘价\", 'pre_close':\"昨收价(前复权)\",\n",
    "       'change':\"涨跌额\", 'pct_chg':\"涨跌幅\", 'vol':\"成交量 （手）\", 'amount':\"成交额 （千元）\"})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "daccf370",
   "metadata": {},
   "outputs": [],
   "source": [
    "df2.columns.tolist()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e206f985",
   "metadata": {},
   "outputs": [],
   "source": [
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a10f57d8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# df.to_dict(orient=\"records\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d4ca7552",
   "metadata": {},
   "outputs": [],
   "source": [
    "code=\"000001.SZ\"\n",
    "start_date=\"20231101\"\n",
    "end_date=\"20231123\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5902fe0f",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4788be18",
   "metadata": {},
   "outputs": [],
   "source": [
    "file_name = f\"{code}_{start_date}_{end_date}_数据.csv\"\n",
    "file_path = os.path.join(os.path.abspath(os.path.dirname(os.getcwd())), \"股票数据\")\n",
    "if not os.path.exists(file_path):\n",
    "    os.mkdir(file_path)\n",
    "csv_file_path = os.path.join(file_path,file_name)\n",
    "df.to_csv(csv_file_path, index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1825cacf",
   "metadata": {},
   "outputs": [],
   "source": [
    "file_name"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5094906e",
   "metadata": {},
   "outputs": [],
   "source": [
    "df.to_csv(r\"D:\\zs\\000001.SZ_20231101_20231123_数据.csv\",index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "781bdc59",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
